// 定义全局变量
var container, scene, camera, renderer, controls;
var keyboard = new THREEx.KeyboardState();
var clock = new THREE.Clock;
var movingCube;
var collideMeshList = [];
var cubes = [];
var message = document.getElementById("message");
var crash = false;
var score = 0;

var scoreText = document.getElementById("score");
var score1=document.getElementById('score1');
var score11=0;

var frag=false;//是否结束
var pass=false;//是否通关

var id = 0;
var crashId = " ";
var lastCrashId = " ";


var music=[0,0,0,1,2,2,1,3,2,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,
    3,2,3,4,5,2,3,5,2,1,3,4,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,4,
    5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,2,1,3,4,3,3,2,3,4,5,2,3,5,3,5,
    3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,4,5,2,3,5,2,1,3,4,
    3,3,2,3,4,5,2,3,5,2,1,3,4,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,2,
    1,3,4,3,3,2,3,4,5,2,3,5,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,2,1,3,4,3,3,
    2,3,4,5,2,3,5,3,5,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,
    4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,
    2,3,5,2,1,3,4,3,2,1,3,4,3,3,2,3,4,5,2,3,5,3,5,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,
    3,5,2,1,3,4,3,2,1,3,4,3,3,2,3,4,5,2,3,5,3,5, 3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,
    3,2,3,4,5,2,3,5,2,1,3,4,3,4,5,2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,4,5,
    2,3,5,2,1,3,4,3,3,2,3,4,5,2,3,5,2,1,3,4,3,2,1];



var d=0;
var a=0;
var c=100;

var crashtimes=3;

var back=document.getElementById('back');
var passgame=document.getElementById('passgame');
var aud1 = document.getElementById("sound");

if(!frag)
{
init();
animate();
}


//init方法：
function init()
{

    scoreText.innerText="Loading...";
//初始化场景
    scene=new THREE.Scene();
    var screenWidth=300;
    var screenHeight=550;
//初始化相机
    camera=new THREE.PerspectiveCamera(45,300/550,1,20000);
    camera.position.set(0,170,400);
//初始化渲染器
    if(Detector.webgl)
    {renderer=new THREE.WebGLRenderer({antialias:true});}
    else
    {renderer=new THREE.CanvasRenderer();}
    renderer.setSize(screenWidth,screenHeight);

    container=document.getElementById("ThreeJS")
    container.appendChild(renderer.domElement);

    THREEx.WindowResize(renderer,camera);
    controls=new THREE.OrbitControls(camera,renderer.domElement);

//五条直线
    
    geometry=new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(-90,-1,-2000));
    geometry.vertices.push(new THREE.Vector3(-90,-1,200));
    material=new THREE.LineBasicMaterial({color:0x6699FF,linewidth:5,fog:true});
    var line1=new THREE.Line(geometry,material);
    scene.add(line1);

    geometry=new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(90,-1,-2000));
    geometry.vertices.push(new THREE.Vector3(90,-1,200));
    material=new THREE.LineBasicMaterial({color:0x6699FF,linewidth:5,fog:true});
    var line2=new THREE.Line(geometry,material);
    scene.add(line2);

    geometry=new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(0,-1,-2000));
    geometry.vertices.push(new THREE.Vector3(0,-1,200));
    material=new THREE.LineBasicMaterial({color:0x6699FF,linewidth:5,fog:true});
    var line3=new THREE.Line(geometry,material);
    scene.add(line3);
    
    geometry=new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(-50,-1,-2000));
    geometry.vertices.push(new THREE.Vector3(-50,-1,200));
    material=new THREE.LineBasicMaterial({color:0x6699FF,linewidth:5,fog:true});
    var line4=new THREE.Line(geometry,material);
    scene.add(line4);

    geometry=new THREE.Geometry();
    geometry.vertices.push(new THREE.Vector3(50,-1,-2000));
    geometry.vertices.push(new THREE.Vector3(50,-1,200));
    material=new THREE.LineBasicMaterial({color:0x6699FF,linewidth:5,fog:true});
    var line5=new THREE.Line(geometry,material);
    scene.add(line5);

//控制的cube
    var cubeGeometry=new THREE.CubeGeometry(25,12,30,5,5,5);
    var wireMaterial=new THREE.MeshBasicMaterial({color:0x00ff00,wireframe:true});
    movingCube=new THREE.Mesh(cubeGeometry,wireMaterial);
   movingCube.position.set(0,5,-20);
   scene.add(movingCube);


}



//animate方法：
function animate()
{
    if(!frag)
    {
    requestAnimationFrame(animate);
    update();
    renderer.render(scene,camera);
    }
}




//update方法：
function update() {
    
    aud1.play();
    aud1.onended = function() {
        pass=true;

        document.getElementById('ai1').style.display="none";
        document.getElementById('aixin1').style.display = "none";
        document.getElementById('ai2').style.display="none";
        document.getElementById('aixin2').style.display = "none";
        document.getElementById('ai3').style.display="none";
        document.getElementById('aixin3').style.display = "none";
    scoreText.innerText=" ";
    score11=score;
    over();
};
    
//第一种玩法
var delta = clock.getDelta();
var moveDistance = 200 * delta;
//console.log(moveDistance);
var rotateAngle = Math.PI / 2 * delta;

if (keyboard.pressed("left") || keyboard.pressed("A")) {
    if (movingCube.position.x > -70)
        movingCube.position.x -= moveDistance;
        /*
    if (camera.position.x > -150) {
        camera.position.x -= moveDistance * 0.3;
        if (camera.rotation.z > -5 * Math.PI / 180) {
            camera.rotation.z -= 0.2 * Math.PI / 180;
        }

    }
    */
}
if (keyboard.pressed("right") || keyboard.pressed("D")) {
    if (movingCube.position.x < 70)
        movingCube.position.x += moveDistance;
        /*
    if (camera.position.x < 150) {
        camera.position.x += moveDistance * 0.3;
        if (camera.rotation.z < 5 * Math.PI / 180) {
            camera.rotation.z += 0.2 * Math.PI / 180;
        }
    
    }    */
}

if (!(keyboard.pressed("left") || keyboard.pressed("right") ||
    keyboard.pressed("A") || keyboard.pressed("D"))) {
    delta = camera.rotation.z;
    camera.rotation.z -= delta / 10;
}
  



//第二种玩法
   if (keyboard.pressed("Z")) 
   { movingCube.position.x  =-70;   }
   if (keyboard.pressed("X")) 
   { movingCube.position.x =-25;   }
   if (keyboard.pressed("N")) 
   { movingCube.position.x =25;    }
   if (keyboard.pressed("M")) 
   { movingCube.position.x =70;    }




    var originPoint = movingCube.position.clone();

    for (var vertexIndex = 0; vertexIndex < movingCube.geometry.vertices.length; vertexIndex++) {
        // 顶点原始坐标
        var localVertex = movingCube.geometry.vertices[vertexIndex].clone();
        // 顶点经过变换后的坐标
        var globalVertex = localVertex.applyMatrix4(movingCube.matrix);
        var directionVector = globalVertex.sub(movingCube.position);

        var ray = new THREE.Raycaster(originPoint, directionVector.clone().normalize());
        var collisionResults = ray.intersectObjects(collideMeshList);
        if (collisionResults.length > 0 && collisionResults[0].distance < directionVector.length()) {
            crash = true;
            crashId = collisionResults[0].object.name;
            break;
        }
        crash = false;
    }

    //补充代码：
    if(crash)
    {
        //message.innerText="crash";
        movingCube.material.color.setHex(0x346386);
        console.log("Crash");
        if(crashId!==lastCrashId)
        {
           if(crashtimes>0)
           {
            document.getElementById('ai'+crashtimes).style.display="block";
            document.getElementById('aixin'+crashtimes).style.display = "none";
            
            crashtimes--;
           }
           if(crashtimes==0)
           {
               score11=score;
               over();
               crashtimes--;
           }
           /*
           else
           {
            scoreText.display='none';
           }
*/
            /*score+=1;*/
            lastCrashId=crashId;

        }
        document.getElementById("explode_sound").play();
    }
    else
    {
        //message.innerText="Safe";
        movingCube.material.color.setHex(0x00ff00);
    }
/*
    if(Math.random()<0.03 && cubes.length<30)
    {makeRandomCube();}
*/
d++;
if(d==c)
{
    for(var i=0;i<music[a];i++)
    {
        makeRandomCube();
    }
    a++;
    if(a==20)
    {c=c/2;}
    d=0;
}


    for(i=0;i<cubes.length;i++)
    {
        if(cubes[i].position.z>camera.position.z)
        {
            scene.remove(cubes[i]);
            cubes.splice(i,1);
            collideMeshList.splice(i,1);
        }
        else{cubes[i].position.z+=10;}
    }

    score+=0.1;
    if(frag==false)
    {
    scoreText.innerText="得分："+Math.floor(score);
    }
    else
    {
    scoreText.innerText=" ";
    }


    

}


// 返回一个介于min和max之间的随机数
function getRandomArbitrary(min, max) {
    return Math.random() * (max - min) + min;
}

// 返回一个随机数
function getRandomArbitrary1() {
    var r=Math.random()*4;
        
    if(r<1) return -70;
    if(r<2&&r>=1) return -25;
    if(r<3&&r>=2) return 25;
    if(r<4&&r>=3) return 70;
    
}

// 返回一个介于min和max之间的整型随机数
function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

//makeRandomCube方法：
function makeRandomCube()
{

  
    var Geometry=new THREE.CubeGeometry(25,12,30);
    var Material=new THREE.MeshBasicMaterial({color:0x00ff00});
    var object=new THREE.Mesh(Geometry,Material);



    var box=new THREE.BoxHelper(object);
    box.material.color.setHex(0xff0000);
    box.position.x=getRandomArbitrary1();
    box.position.y=1;
    box.position.z=getRandomArbitrary(-1000,-1400);
    cubes.push(box);
    box.name="box_"+id;
    id++;
    collideMeshList.push(box);
    scene.add(box);


}
function over()
{
    frag=true;
    if(pass)
    {
    passgame.style.display='block';

    }
    else
    {
    back.style.display='block';
    }
    document.getElementById('ai1').style.display="none";
    document.getElementById('ai2').style.display="none";
    document.getElementById('ai3').style.display="none";

    document.getElementById("explode_sound").muted = true;
    document.getElementById("sound").muted = true;

    score1.innerHTML=Math.floor(score11);
    


 

}